package cn.vivi.blog.service.impl;

import cn.vivi.blog.client.ClassesServiceClient;
import cn.vivi.blog.client.TagServiceClient;
import cn.vivi.blog.entity.vo.BlogVo;
import cn.vivi.blog.mapper.BlogMapper;
import cn.vivi.blog.service.ArticleService;
import cn.vivi.blog.service.BlogService;
import cn.vivi.common.entity.Article;
import cn.vivi.common.entity.Blog;
import cn.vivi.common.entity.Classes;
import cn.vivi.common.entity.Tag;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;


@Service
@Transactional
public class BlogServiceImpl implements BlogService {

    @Autowired
    private BlogMapper blogMapper;

    @Autowired
    private ArticleService articleService;

    @Autowired
    private TagServiceClient tagServiceClient;

    @Autowired
    private ClassesServiceClient classesServiceClient;

    @Override
    public BlogVo findBlogById(String id) {
        BlogVo blogVo = new BlogVo();
        Article article = articleService.findByBlogId(id);
        List<Tag> tags = tagServiceClient.findByBlogId(id).getResult();
        Classes classes = classesServiceClient.findById(id).getResult();
        Blog blog = blogMapper.selectById(id);
        blog.setArticle(article);
        blogVo.setBlog(blog);
        blogVo.setClasses(classes);
        blogVo.setTags(tags);
        return blogVo;
    }

    @Override
    public Page<BlogVo> findBlogByPage(long current, long size) {
        ArrayList<BlogVo> vos = new ArrayList<>(20);
        Page<Blog> blogPage = blogMapper.selectPage(new Page<>(current, size), null);
        List<Blog> blogs = blogPage.getRecords();
        Page<BlogVo> voPage = new Page<>();
        if (blogs.size() > 0) {
            blogs.forEach(b -> {
                BlogVo vo = new BlogVo();
                vo.setBlog(b);
                vo.setTags(tagServiceClient.findByBlogId(b.getId()).getResult());
                vo.setClasses(classesServiceClient.findById(b.getClassesId()).getResult());
                vos.add(vo);
            });
            voPage.setRecords(vos);
            voPage.setTotal(blogPage.getTotal());
            return voPage;
        }
        return voPage;
    }

}
